package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.UserLoginMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {


    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Value("${sky.wechat.appid}")
    private String appid;
    @Value("${sky.wechat.secret}")
    private String secret;

    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {
        String openId = getOpenid(dto.getCode());
        if (!StringUtils.hasText(openId)){
            throw new BaseException("未获取到微信的openid");
        }

        User user = userLoginMapper.getByOpenId(openId);
        if (user == null){
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openId);
            userLoginMapper.insert(user);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("openid",openId);
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        Merchant merchant = merchantMapper.selectById(1L);

        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, dto.getLocation());

        UserLoginVO loginVo = UserLoginVO.builder().token(token)
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();

        return Result.success(loginVo);
    }

    private String getOpenid(String code){
        Map<String,String> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String response = HttpClientUtil.doGet(URL,map);
        JSONObject jsonObject = JSONObject.parseObject(response);
        log.info("微信返回登录：{}",jsonObject);
        return (String)jsonObject.get("openid");
    }


}
